package com.wjh.www.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * @author wjh
 * @date 2021/9/11 12:25
 * @Package com.wjh.anyview.util
 */
public class ControllerUtil {

    /**
     * 转化为json格式的数据并传给前端的静态方法
     *
     * @param resp HttpServletResponse resp
     * @param obj  以json格式传给前端的对象
     */
    public static void toJson(HttpServletResponse resp, Object obj) throws IOException {
        String json = "{}";
        json = new ObjectMapper().writeValueAsString(obj);
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        pw.println(json);
        pw.flush();
        pw.close();
    }

    /**
     * 把文件传递给前端
     *
     * @param resp     resp
     * @param fileName 文件名
     */
    public static void setResponseHeaderWithFile(HttpServletResponse resp, String fileName) throws UnsupportedEncodingException {
        fileName = new String(fileName.getBytes(), "ISO8859-1");
        resp.setContentType("application/octet-stream;charset=ISO8859-1");
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        resp.addHeader("Pargam", "no-cache");
        resp.addHeader("Cache-Control", "no-cache");
    }

    /**
     * 传输excel表格给前端
     *
     * @param resp     响应
     * @param fileName excel名
     * @param wb       excel
     */
    public static void pushExcel(HttpServletResponse resp, String fileName, HSSFWorkbook wb) throws IOException {
        setResponseHeaderWithFile(resp, fileName);
        OutputStream os = resp.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }
}
